package service

import (
	"github.com/go-xorm/xorm"
	"time"
)

// AdminService 管理员服务
type AdminService interface {

	// AdminLoginByUsernameAndPassword 通过用户名和密码获取管理员
	AdminLoginByUsernameAndPassword(username, password string) ([]map[string]string, bool)

	// GetAllUsers 获取所有的用户信息
	GetAllUsers() []map[string]string

	// AddVoucher 新增一行金券数据
	AddVoucher(amount int, code string, createdTime time.Time) bool

	// GetAllVouchers 获取所有的金券信息
	GetAllVouchers() []map[string]string

	// DeleteVoucher 删除指定id的一行金券数据
	DeleteVoucher(id int) bool
}

// NewAdminService 创建一个新的管理员服务对象
func NewAdminService(engine *xorm.Engine) AdminService {
	return &adminService{
		Engine: engine,
	}
}

// 管理员服务结构体
type adminService struct {
	Engine *xorm.Engine
}

// AdminLoginByUsernameAndPassword 通过用户名和密码获取管理员
func (as adminService) AdminLoginByUsernameAndPassword(username, password string) ([]map[string]string, bool) {

	// 通过用户名和密码登录管理员账户
	sqlStr := "SELECT id FROM ( SELECT * FROM user LIMIT 1 ) admin WHERE username = ? and password = ?"
	results, err := as.Engine.QueryString(sqlStr, username, password)
	if err != nil {
		panic(err.Error())
	}
	return results, err == nil
}

// GetAllUsers 获取所有的用户信息
func (as adminService) GetAllUsers() []map[string]string {

	// 获取所有用户的id、用户名、昵称、性别、余额
	sqlStr := "SELECT id, username, nickname, sex, balance	FROM user"
	results, err := as.Engine.QueryString(sqlStr)
	if err != nil {
		return nil
	}
	return results
}

// AddVoucher 新增一行金券数据
func (as adminService) AddVoucher(amount int, code string, createdTime time.Time) bool {

	// 插入一行金券新数据
	sqlStr := "INSERT INTO voucher (amount, code, created_time) values (?, ?, ?)"
	_, err := as.Engine.Exec(sqlStr, amount, code, createdTime)
	return err == nil
}

// GetAllVouchers 获取所有的金券信息
func (as adminService) GetAllVouchers() []map[string]string {

	// 获取所有金券的id，数额，创建时间，兑换码，使用id，使用时间
	sqlStr := "SELECT id, amount, created_time, code, user_id, used_time FROM voucher"
	results, err := as.Engine.QueryString(sqlStr)
	if err != nil {
		panic(err.Error())
	}
	return results
}

// DeleteVoucher 删除指定id的一行金券数据
func (as adminService) DeleteVoucher(id int) bool {

	// 删除一行金券数据
	sqlStr := "DELETE FROM voucher WHERE id = ?"
	_, err := as.Engine.Exec(sqlStr, id)
	return err == nil
}
